package com.bw.a2209clubshop.base

import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

open class BaseViewModel:ViewModel(){
    fun <M:BaseResponse<T>,T> execute(
        action:Flow<M>,
        onStart:(suspend ()->Unit)?=null,
        onError:(suspend (String)->Unit)?=null,
        onFinish:(suspend (M)->Unit)?=null,
    )=viewModelScope.launch {
        action.onStart {
            onStart?.invoke()
        }.catch { err->
            onError?.invoke(err.message.toString())
        }.collect {
            if (it.code==200){
                onFinish?.invoke(it)
            }else{
                onError?.invoke(it.msg)
            }
        }
    }


}